package com.example.musicrunner.media;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.example.musicrunner.R;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.ListActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MusicActivity extends ListActivity {
	private static final String SD_Path = new String("/sdcard/");
	private List<String> songs = new ArrayList<String>();
	private MediaPlayer player = new MediaPlayer();

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_music);
		updatePlayList();
		
	Button end = (Button) findViewById(R.id.stopBtn);
	end.setOnClickListener(new OnClickListener() {
	   @Override
	   public void onClick(View v) {
	   player.stop();
	   }
	});
}

@Override
protected void onListItemClick(ListView list, View view, int position, long id) {
	try {
		player.reset();
		player.setDataSource(SD_Path+songs.get(position));
		player.prepare();
		player.start();
	} catch (IOException e) {
		Log.v(getString(R.string.app_name), e.getMessage());
	}
}
	
	private void updatePlayList() {
	File home = new File(SD_Path);
	if(home.listFiles(new Mp3Filter()).length > 0){
		for(File file:home.listFiles(new Mp3Filter())){
			songs.add(file.getName());
		}
	}
		ArrayAdapter<String> songList = new ArrayAdapter<String>(this,R.layout.song_item,songs);
	    setListAdapter(songList);
	}
	
@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
}

class Mp3Filter implements FilenameFilter {
	public boolean accept(File dir, String name) {
		return(name.endsWith(".mp3"));
	}
}	


